package day3;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.ByteToMessageCodec;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class HelloClient {
    public static void main(String[] args) throws InterruptedException {
        //1.启动类
        Channel channel = new Bootstrap()
                //添加eventLoop
                .group(new NioEventLoopGroup(1))
                //选择客户端
                .channel(NioSocketChannel.class)
                //4.添加处理器
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new ByteToMessageCodec<byte[]>() {
                            @Override
                            protected void encode(ChannelHandlerContext ctx, byte[] msg, ByteBuf out) throws Exception {
                                System.out.println(msg);
                                out.writeBytes(msg);
                            }

                            @Override
                            protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
                                System.out.println(in.array());
                                out.add(in.array());
                            }
                        });
                        ch.pipeline().addLast(new SimpleChannelInboundHandler<byte[]>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, byte[] msg) throws Exception {
                                
                            }
                        });
                    }
                })
                .connect(new InetSocketAddress("localhost", 8081))
                .sync()
                .addListener(f->{
                    if (f.isSuccess()) {
                        System.out.println(2222222);
                    }
                })
                .channel();
        channel.writeAndFlush(new byte[]{0x11,0x12,0x13});

    }

}
